package android.support.v7.widget;

import android.content.Context;
import android.util.AttributeSet;

public class ExtraRecyclerView extends RecyclerView {

    public interface OnLoadMoreListener {

        void onLoadMore();

    }

    private OnLoadMoreListener onLoadMoreListener;

    private int loadMoreCount;

    private boolean loadMore;

    public ExtraRecyclerView(Context context) {
        super(context);
        init();
    }

    public ExtraRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ExtraRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        this.onLoadMoreListener = onLoadMoreListener;
    }

    public boolean isLoadMore() {
        return loadMore;
    }

    public void setLoadMore(boolean loadMore) {
        this.loadMore = loadMore;
    }

    public int getLoadMoreCount() {
        return loadMoreCount;
    }

    public void setLoadMoreCount(int loadMoreCount) {
        this.loadMoreCount = loadMoreCount;
    }

    private void init() {
        setOnScrollListener(new ExtraOnScrollListener());
    }

    private class ExtraOnScrollListener extends OnScrollListener {

        public ExtraOnScrollListener() {
            super();
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {

        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            int lastVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
            int totalItemCount = recyclerView.getLayoutManager().getItemCount();
            if (lastVisibleItem >= totalItemCount - 1 - loadMoreCount && dy > 0) {
                if (!loadMore) {
                    loadMore = true;
                    onLoadMoreListener.onLoadMore();
                }
            }
        }
    }

}